import {
    Component, OnInit, Output, Input, EventEmitter, ViewChild, TemplateRef, OnDestroy, Injector
} from '@angular/core';
import { NotifyService } from '@farris/ui-notify';
import { FormBasicService, DesignerEnvType, SchemaService } from '@farris/designer-services';
import { FarrisMetadataDto } from '@farris/designer-services';
import { ResolveTemplateFieldUtil } from '../resolve-template-fields';
import { TemplateBindingEditorComponent } from '../../../../list-view/property/editor/template-binding-editor/template-binding-editor.component';
import { HttpClient, HttpHeaders } from '@angular/common/http';


@Component({
    selector: 'app-place-template-editor',
    templateUrl: './place-template-editor.component.html'
})
export class PlaceTemplateEditorComponent implements OnInit, OnDestroy {
    @Output() closeModal = new EventEmitter<any>();
    @Output() submitModal = new EventEmitter<any>();
    @Input() value;
    @Input() editorParams = { id: null, placeDataSource: { voId: '', formId: '' }, placeDataSourceUrl: '', placeDataSourceUrlType: '' };

    @ViewChild('footer') modalFooter: TemplateRef<any>;
    modalConfig = {
        title: '模板编辑器',
        width: 1000,
        height: 700,
        showButtons: true,
        showMaxButton: true
    };

    @ViewChild(TemplateBindingEditorComponent) templateCmp: TemplateBindingEditorComponent;

    /** 模板编辑器的组件需要的入参 */
    templateBindingEditorParams;

    /** 零代码元数据接口 */
    private loadMetaDataURL = '/api/dev/nocode/v1.0/micro-apps/metadatas';

    /** 请求服务 */
    private http: HttpClient;
    private headerOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };

    constructor(
        private formBasicServ: FormBasicService,
        private notifyService: NotifyService,
        private injector: Injector,
        private schemaServ: SchemaService,) {

        this.http = this.injector.get(HttpClient);
    }

    ngOnInit(): void {

        this.templateBindingEditorParams = {
            listViewId: this.editorParams.id,
            templateUri: 'assets/form/preset-template/appointment-calendar-template.json',
            schemaFields: [],
            viewModelId: null
        };
        switch (this.formBasicServ.envType) {
            case DesignerEnvType.designer: {
                this.getSchemaFieldsFromVo();
                break;
            }
            case DesignerEnvType.noCode: {
                this.getSchemaFieldsFromForm();
                break;
            }
            default: {
                this.notifyService.warning('暂不支持。');
            }
        }

        this.templateCmp.submitModal.subscribe(data => {
            this.submitModal.emit(data);
        });
    }

    ngOnDestroy(): void {

    }

    /**
     * 低代码：根据地点VO元数据id，获取VO对应的schema字段列表
     */
    private getSchemaFieldsFromVo() {
        if (!this.editorParams.placeDataSource || !this.editorParams.placeDataSource.voId) {
            return;
        }

        const sessionId = '';
        this.schemaServ.converVO2Schema(this.editorParams.placeDataSource.voId, sessionId).subscribe(data => {
            if (data) {
                const fieldServ = new ResolveTemplateFieldUtil();
                const schemaFields = fieldServ.getSimpleTableFieldsByBindTo(data.entities, '/');
                this.templateBindingEditorParams.schemaFields = schemaFields;
            }
        }, () => {
            this.notifyService.error('获取视图对象元数据失败');
        });
    }
    /**
     * 零代码：根据地点表单form元数据id,获取表单中记录的voId，然后根据voId获取vo对应的schema字段列表
     */
    private getSchemaFieldsFromForm() {

        this.http.get(`${this.loadMetaDataURL}/${this.editorParams.placeDataSource.formId}`, this.headerOptions).subscribe((data: FarrisMetadataDto) => {
            if (data && data.content) {
                let domJson;
                if ('' + data.content === data.content) {
                    domJson = JSON.parse(data.content);
                } else {
                    domJson = data.content;
                }
                const schema = domJson.Contents.module.schemas[0];

                const voId = schema.id;
                this.schemaServ.convertVoToSchemaForNoCodeForm(voId).subscribe(newSchema => {
                    const fieldServ = new ResolveTemplateFieldUtil();
                    const schemaFields = fieldServ.getSimpleTableFieldsByBindTo(newSchema.entities, '/');
                    this.templateBindingEditorParams.schemaFields = schemaFields || [];
                }, () => {
                    this.notifyService.error('获取视图对象元数据失败');
                });

            }
        }, () => {
            this.notifyService.error('获取表单元数据失败');
        });
    }


    clickConfirm() {
        this.templateCmp.clickConfirm();
    }

    clickCancel() {
        this.templateCmp.clickCancel();
        this.closeModal.emit();
    }
}
